import 'dart:async';

import 'package:app_installer/app_installer.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../../widgets/TextView.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';

import '../../model/UpdateEntity.dart';
import '../../utils/Toast/MyTosat.dart';
import '../../utils/color/ColorUtils.dart';
import '../../utils/file/DownFile.dart';
import '../../utils/file/FileReadWrite.dart';
import '../../utils/permission/PermissionUtils.dart';

class UpdateDialog extends StatefulWidget {
  UpdateDialog({Key? key, required this.updateEntity}) : super(key: key);
  UpdateEntity updateEntity;

  @override
  State<UpdateDialog> createState() => _UpdateDialogState();
}

class _UpdateDialogState extends State<UpdateDialog> {
  var title;
  var _progressValue = 0.0;
  var content;
  var visible = false;
  StreamController<String> streamController = StreamController.broadcast();

  @override
  void initState() {
    // TODO: implement initState
    title = "${"version".tr} v${widget.updateEntity.name}";
    content = widget.updateEntity.content;
    super.initState();
  }

  downApk(bool install) async {
    String localPath = await DownFile.getPhoneLocalPathCps();
    String savePath = "${localPath}/apk/${widget.updateEntity.version}.apk";
    print("savePath$savePath");

    if (install) {
      bool installAppPermission =
          await PermissionUtils.checkInstallAppPermission();
      if (installAppPermission) {
        //YcPluginLearn.installApp(savePath, kAndroidPackageId);
      }
      return;
    }

    setState(() {});
    //如果本地有该文件，则先删除
    await FileReadWrite.fileDelete(savePath);
    streamController.sink.add("0");
    CancelToken cancelToken = CancelToken();
    DownFile.download(
        cancelToken: cancelToken,
        url: widget.updateEntity.downloadurl!,
        savePath: savePath,
        onReceiveProgress: (current, total) async {
          //实时进度
          double p = current / total * 100;
          int perInt = p.truncate();
          streamController.sink.add("${perInt}");
        },
        done: () async {
          //下载完成
          streamController.sink.add("0");
          setState(() {});
          // YcPluginLearn.installApp(savePath, kAndroidPackageId);
          installApk(savePath);
        },
        failed: (err) {
          //下载出错
          MyToast().show("下载出错了");
          streamController.sink.add("0");
        },
        onCancel: () {
          //暂停
        });
  }

  //安装APK
  void installApk(String Path) {}

  _networkInstallApk(String fileUrl) async {
    if (_progressValue != 0 && _progressValue < 1) {
      print("Wait a moment, downloading");
      return;
    }

    _progressValue = 0.0;
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/takeaway_phone_release_1.apk";
    // File file = File(savePath);
    // bool exists = await file.exists();
    // if (exists) {
    //   AppInstaller.installApk(savePath).catchError(() {
    //     print("错误1");
    //   });
    //   return;
    // }
    await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
      final value = count / total;
      if (_progressValue != value) {
        setState(() {
          if (_progressValue < 1.0) {
            _progressValue = count / total;
          } else {
            _progressValue = 0.0;
          }
        });
        content =
            "${"downloading".tr} ${(_progressValue * 100).toStringAsFixed(0)}%";
        setState(() {});
      }
    });
    AppInstaller.installApk(savePath).catchError(() {
      print("错误2");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(6))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          TextView(
            title,
            alignment: Alignment.centerLeft,
            style: TextStyle(
                color: rgba(48, 49, 51, 1),
                fontSize: 18,
                fontWeight: FontWeight.bold),
          ),
          const SizedBox(
            height: 24,
          ),
          Text(
            content,
            textAlign: TextAlign.start,
            strutStyle:
                StrutStyle(forceStrutHeight: true, height: 2, leading: 0.4),
            maxLines: 10,
          ),
          Visibility(
            visible: visible,
            child: LinearProgressIndicator(
              value: _progressValue,
              backgroundColor: rgba(247, 247, 247, 1),
              borderRadius: BorderRadius.circular(2),
              valueColor: const AlwaysStoppedAnimation<Color>(Colors.redAccent),
            ),
          ),
          const SizedBox(
            height: 40,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextView(
                "cancel".tr,
                alignment: Alignment.center,
                textAlign: TextAlign.center,
                height: 44,
                padding: const EdgeInsets.symmetric(horizontal: 45),
                radius: BorderRadius.circular(6),
                backcolor: rgba(247, 247, 247, 1),
                style: TextStyle(color: ColorUtils.text_),
                onclick: () {
                  Get.back();
                },
              ),
              const SizedBox(
                width: 16,
              ),
              TextView(
                "update".tr,
                alignment: Alignment.center,
                textAlign: TextAlign.center,
                height: 44,
                padding: const EdgeInsets.symmetric(horizontal: 45),
                radius: BorderRadius.circular(6),
                backcolor: rgba(255, 78, 77, 1),
                style: TextStyle(color: Colors.white),
                onclick: () {
                  title = "progress".tr;
                  //downApk(false);
                  visible = true;
                  _networkInstallApk(widget.updateEntity!.downloadurl!);
                },
              ),
            ],
          )
        ],
      ),
    );
  }
}
